#include "unp.h"

void write_time(int fd,sockaddr* cliaddr, socklen_t clilen)
{
  int n;
  fd_set rset;
  socklen_t len;
  char buff[128] = {'\0'};
  time_t ticks;

  for (;;)
  {
    ticks = time(NULL);
    len = clilen;
    if (n = recvfrom(fd,buff,1,0,cliaddr,&len) > 0)
    {
      printf("sever reply\n");
      snprintf(buff,sizeof(buff),"%.24s\r\b",ctime(&ticks));
      sendto(fd,buff,strlen(buff),0,cliaddr,len);
    }       
  }

  printf("end for\n");
  close(fd);
}

int main(int argc, char** argv)
{
  if (argc < 2)
  {
    printf("usage: daytime <host>\n");
    exit(-1);
  }

  struct sockaddr_in sevraddr,cliaddr;
  int sockfd = socket(AF_INET,SOCK_DGRAM,0);
  
  memset(&sevraddr,0,sizeof(sevraddr));
  memset(&cliaddr,0,sizeof(cliaddr));
  
  sevraddr.sin_family = AF_INET;
  inet_pton(AF_INET,argv[1],&sevraddr.sin_addr);
  sevraddr.sin_port = htons(10086);  
  
  bind(sockfd,(struct sockaddr*)(&sevraddr),sizeof(sevraddr));  
  
  fcntl(sockfd,F_SETFL,O_NONBLOCK);
  const int on = 1;
  setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&on,sizeof(on));

  char buff[128] = {'\0'};
  printf("The bind address is: %s\n",inet_ntop(AF_INET,&sevraddr.sin_addr,buff,sizeof(buff)));

  write_time(sockfd,(struct sockaddr*)(&cliaddr),sizeof(cliaddr));

  return 0;
}
